/*
*  Copyright 2019-2020 Zheng Jie
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*  http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*/
package com.alien.admin.modules.container.service.impl;

import com.alien.admin.modules.container.domain.K8sDeploymentStatus;
import com.alien.admin.modules.container.service.dto.K8sProjectQueryCriteria;
import com.alien.admin.modules.deploy.domain.DpServerConfig;
import com.alien.admin.modules.deploy.service.DpServerConfigService;
import com.alien.admin.modules.deploy.service.DpServerService;
import com.alien.admin.modules.deploy.service.dto.DpServerDto;
import com.alien.admin.utils.*;
import lombok.RequiredArgsConstructor;
import com.alien.admin.modules.container.repository.K8sDeploymentStatusRepository;
import com.alien.admin.modules.container.service.K8sDeploymentStatusService;
import com.alien.admin.modules.container.service.dto.K8sDeploymentStatusDto;
import com.alien.admin.modules.container.service.dto.K8sDeploymentStatusQueryCriteria;
import com.alien.admin.modules.container.service.mapstruct.K8sDeploymentStatusMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;

import java.util.List;
import java.util.Map;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.LinkedHashMap;

/**
* @website https://el-admin.vip
* @description 服务实现
* @author zhouseyi
* @date 2021-10-19
**/
@Service
@RequiredArgsConstructor
public class K8sDeploymentStatusServiceImpl implements K8sDeploymentStatusService {

    private final K8sDeploymentStatusRepository k8sDeploymentStatusRepository;
    private final K8sDeploymentStatusMapper k8sDeploymentStatusMapper;
    private final DpServerConfigService dpServerConfigService;
    private final DpServerService dpServerService;

    @Override
    public Map<String,Object> queryAll(K8sDeploymentStatusQueryCriteria criteria, Pageable pageable){
        Page<K8sDeploymentStatus> page = k8sDeploymentStatusRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable);
        return PageUtil.toPage(page.map(k8sDeploymentStatusMapper::toDto));
    }

    @Override
    public List<K8sDeploymentStatusDto> queryAll(K8sDeploymentStatusQueryCriteria criteria){
        return k8sDeploymentStatusMapper.toDto(k8sDeploymentStatusRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder)));
    }

    @Override
    @Transactional
    public K8sDeploymentStatusDto findById(Integer k8sId) {
        K8sDeploymentStatus k8sDeploymentStatus = k8sDeploymentStatusRepository.findById(k8sId).orElseGet(K8sDeploymentStatus::new);
        ValidationUtil.isNull(k8sDeploymentStatus.getK8sId(),"K8sDeploymentStatus","k8sId",k8sId);
        return k8sDeploymentStatusMapper.toDto(k8sDeploymentStatus);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public K8sDeploymentStatusDto create(K8sDeploymentStatus resources) {
        return k8sDeploymentStatusMapper.toDto(k8sDeploymentStatusRepository.save(resources));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(K8sDeploymentStatus resources) {
        K8sDeploymentStatus k8sDeploymentStatus = k8sDeploymentStatusRepository.findById(resources.getK8sId()).orElseGet(K8sDeploymentStatus::new);
        ValidationUtil.isNull( k8sDeploymentStatus.getK8sId(),"K8sDeploymentStatus","id",resources.getK8sId());
        k8sDeploymentStatus.copy(resources);
        k8sDeploymentStatusRepository.save(k8sDeploymentStatus);
    }

    @Override
    public void deleteAll(Integer[] ids) {
        for (Integer k8sId : ids) {
            k8sDeploymentStatusRepository.deleteById(k8sId);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteK8sDeploymentStatus(Integer k8sId, String namepace) {
        k8sDeploymentStatusRepository.deleteAllByNamespaceAndK8sId(namepace, k8sId);
    }

    @Override
    public void download(List<K8sDeploymentStatusDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (K8sDeploymentStatusDto k8sDeploymentStatus : all) {
            Map<String,Object> map = new LinkedHashMap<>();
            map.put(" namespace",  k8sDeploymentStatus.getNamespace());
            map.put(" deploymentName",  k8sDeploymentStatus.getDeploymentName());
            map.put(" replicas",  k8sDeploymentStatus.getReplicas());
            map.put(" updatedReplicas",  k8sDeploymentStatus.getUpdatedReplicas());
            map.put(" readyReplicas",  k8sDeploymentStatus.getReadyReplicas());
            map.put(" availableReplicas",  k8sDeploymentStatus.getAvailableReplicas());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }

    @Override
    public Integer findProjectRunningStatus(K8sProjectQueryCriteria criteria) {
        DpServerConfig dpServerConfig = dpServerConfigService.findDpServerConfig(criteria);
        if(dpServerConfig == null) {
            return DeployConstant.RUNNING_STATUS_UNKNOW;
        }

        DpServerDto dpServer = dpServerService.findById(criteria.getProjectId());
        String deploymentName = String.format("%s-deployment", dpServer.getName());

        K8sDeploymentStatusQueryCriteria k8sDeploymentStatusQueryCriteria = new K8sDeploymentStatusQueryCriteria();
        k8sDeploymentStatusQueryCriteria.setK8sId(dpServerConfig.getK8sInstanceId());
        k8sDeploymentStatusQueryCriteria.setNamespace(dpServerConfig.getK8sNameSpace());
        k8sDeploymentStatusQueryCriteria.setDeploymentName(deploymentName);

        List<K8sDeploymentStatusDto> k8sDeploymentStatusDtoList = queryAll(k8sDeploymentStatusQueryCriteria);
        if(k8sDeploymentStatusDtoList == null || k8sDeploymentStatusDtoList.isEmpty()) {
            return DeployConstant.RUNNING_STATUS_UNKNOW;
        }

        K8sDeploymentStatusDto k8sDeploymentStatusDto = k8sDeploymentStatusDtoList.get(0);
        Integer availableReplicas = k8sDeploymentStatusDto.getAvailableReplicas();
        if(availableReplicas == null) {
            return DeployConstant.RUNNING_STATUS_DEATH;
        }

        return DeployConstant.RUNNING_STATUS_ALIVE;
    }
}
